import {login,logout} from "@/api/login"
import store from '@/store';
const user = {
    namespaced: true,
    state: {
        userInfo: JSON.parse(localStorage.getItem("userInfo")),
        token:localStorage.getItem("token"),
    },
    getters: {},
    mutations: {
        SET_TOKEN: (state, token) => {
            localStorage.setItem("token", token)
            state.token = token
        },
        SET_USERINFO: (state, user) => {
            localStorage.setItem("userInfo", JSON.stringify(user))
            state.userInfo = user
        },
    },
    actions: {
        Login({ commit },userInfo){
            return new Promise((resolve,reject)=>{
                login(userInfo.username,userInfo.password).then(res=>{
                    commit("SET_USERINFO",res.data.data.user)
                    commit("SET_TOKEN",res.data.data.token)
                    resolve()
                }).catch(error=>{
                    reject(error)
                })
            })
        },
        Logout({commit}){
            return new Promise((resolve, reject) => {
                logout().then(res=>{
                    store.commit("menu/INIT_INIT")
                    commit("SET_USERINFO","")
                    commit("SET_TOKEN","")
                    resolve(res)
                }).catch(error=>{
                    reject(error)
                })
            })
        },
        clean({commit}){
            return new Promise((resolve) => {
                commit("SET_USERINFO","")
                commit("SET_TOKEN","")
                resolve()
            })
        }
    },
}

export default user